package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/go-redis/redis/v8"
	"proto"
	"strconv"
)

type User struct {
	// 用户id：数字
	Id int
	// 用户密码：字母数字组合
	Password string
	// 用户昵称：用来显示
	NickName string
	// 用户性别：字符串
	Sex string
	// 用户头像：url
	Purikura string
	// 用户上线登录时间：字符串
	LoginTime string
	// 用户是否在线：online
	Online bool
}

func (user *User)getId()(int,error){
	id,err:=rdb.Incr(ctx,redisPrefix+"user_id").Result()
	return int(id),err
}
func (user *User)CreateUserStr(name, pwd, sex string)error{
	id,err:=user.getId()
	if err!=nil {
		return err
	}


	user.Id=id
	user.NickName=name
	user.Password=pwd
	user.Sex=sex
	bytes,err:=json.Marshal(user)
	if err!=nil {
		return err
	}

	i,err:=rdb.HSetNX(ctx,redisPrefix+"list",name,string(bytes)).Result()
	fmt.Println(name,i,"dfasdfasd",err)
	if err!=nil {
		return err
	}
	if !i {
		return errors.New("昵称重复")
	}
	sid :=strconv.Itoa(id)
	fmt.Println(name,sid,"dfasdfasd")
	i,err=rdb.HSetNX(ctx,redisPrefix+"Id",name,sid).Result()
	if err!=redis.Nil {
		fmt.Println("kkk %v",err)

	}
	if !i {
		fmt.Println("kkk",i)

	}
	rdb.HSetNX(ctx,redisPrefix+"Online",sid,"false").Result()
	rdb.HSetNX(ctx,redisPrefix+"Sex",sid,sex).Result()
	rdb.HSetNX(ctx,redisPrefix+"NickName",sid,name).Result()
	rdb.HSetNX(ctx,redisPrefix+"Password",sid,pwd).Result()
	rdb.HSetNX(ctx,redisPrefix+"LoginTime",sid,"0").Result()
	return nil
}
func(user *User)login()(string,error){
	id,err:=rdb.HGet(ctx,redisPrefix+"Id",user.NickName).Result()
	if err!=redis.Nil {
		return "",err
	}
	password,err:=rdb.HGet(ctx,redisPrefix+"Password",user.Password).Result()
	fmt.Println(password,"+",user.Password)
	if err!=redis.Nil||password!=user.Password {
		return "",errors.New("账号或密码错误")
	}
	_=rdb.HSet(ctx,redisPrefix+"Online",id,"true")
	return id,nil
}
func AllList()(*[]proto.UserInfo,error)  {

	hLen,err:=rdb.HLen(ctx,redisPrefix+"Id").Result()

	if err!=nil {
		return nil,err
	}

	userInfos := make([]proto.UserInfo,hLen)

	mId,err:=rdb.HGetAll(ctx,redisPrefix+"Id").Result()
	if err!=nil {
		return nil,err
	}

	mOnline,err:=rdb.HGetAll(ctx,redisPrefix+"Online").Result()
	if err!=nil {
		return nil,err
	}
	mSex,err:=rdb.HGetAll(ctx,redisPrefix+"Sex").Result()
	if err!=nil {
		return nil,err
	}

	i:=0
	for k,v :=range mId{
		userInfos[i].NickName=k
		userInfos[i].Online,_=strconv.ParseBool(mOnline[v])
		userInfos[i].Sex=mSex[v]
		i++
	}
	return &userInfos,nil
}

